package com.suitsoft.ut.web.imp;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springside.modules.utils.web.struts2.Struts2Utils;

import com.google.common.collect.Lists;
import com.opensymphony.xwork2.ActionSupport;
import com.suitsoft.ut.commons.LogAnnotation;
import com.suitsoft.ut.commons.UserHolder;
import com.suitsoft.ut.entity.base.StudentTemp;
import com.suitsoft.ut.service.base.ExcelDataStudent;
import com.suitsoft.ut.service.base.StudentTempManager;
import com.suitsoft.ut.util.DateUtils;
import com.suitsoft.ut.util.ExcelDataError;

/**
 * 导入学生信息
 *@author Suine
 */
public class StudentDataAction extends ActionSupport{
	/**
	 * 
	 */
	private static final long serialVersionUID = -6233655948454639753L;

	/** 日志输出对象 */
	protected final Logger logger = LoggerFactory.getLogger(getClass());
	
	private StudentTempManager studentTempManager;
	
	/** 每次获取剩余记录的条数*/
	private final int SHOUYU_COUNT = 50;
	
	/** 上传文件 */
	private File uploadFile;
	/** 上传文件名 */
	private String uploadFileFileName;
	/** 房表文件类型 */
	private String uploadFileContentType;
	List<ExcelDataError> excelErrors;
	/** 临时数据集 */
	private List<ExcelDataStudent> tempList;
	
	
	@Override
	public String execute() throws Exception {
		cleanSession();
		return super.execute();
	}
	
	/**
	 * 清除Session
	 */
	private void cleanSession(){
		Struts2Utils.getSession().removeAttribute("studentDataExcelErrors");
		Struts2Utils.getSession().removeAttribute("studentDataExcelData");
		Struts2Utils.getSession().removeAttribute("studentDataNowIdx");
	}

	/**
	 * 上传
	 * @return
	 */
	@LogAnnotation(log = "基础数据导入 - 学生 - excel导入")
	public String upload(){
		try {
			try {
				cleanSession();
				excelErrors = Lists.newArrayList();
				List<ExcelDataStudent> studentData = studentTempManager.handleData(uploadFile, excelErrors);
				Struts2Utils.getSession().setAttribute("studentDataExcelErrors", excelErrors);
				Struts2Utils.getSession().setAttribute("studentDataExcelData", studentData);
			} catch (Exception e) {
				Struts2Utils.getResponse().sendError(504,"啥");
				e.printStackTrace();
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return SUCCESS;
	}
	
	/**
	 * 上传确认页面
	 */
	@SuppressWarnings("unchecked")
	public String input(){
		excelErrors = (List<ExcelDataError>)Struts2Utils.getSessionAttribute("studentDataExcelErrors");
		if(excelErrors == null){
			return SUCCESS;
		}
		if(excelErrors.isEmpty()){
			tempList = (List<ExcelDataStudent>)Struts2Utils.getSessionAttribute("studentDataExcelData");
			if(tempList == null || tempList.size() == 0){
				addActionMessage("未读到数据！");
				return SUCCESS;
			}
		}
		Struts2Utils.getSession().removeAttribute("studentDataNowIdx");
		return INPUT;
	}
	
	/**
	 * 获取下个50个记录
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public String getDown(){
		excelErrors = (List<ExcelDataError>)Struts2Utils.getSessionAttribute("studentDataExcelErrors");
		if(excelErrors == null){
			return SUCCESS;
		}
		
		tempList = (List<ExcelDataStudent>)Struts2Utils.getSessionAttribute("studentDataExcelData");
		Object obj = Struts2Utils.getSession().getAttribute("studentDataNowIdx");
		int nowInx = 0;
		int toInx = 0;
		if(obj == null){
			Struts2Utils.getSession().setAttribute("studentDataNowIdx", SHOUYU_COUNT);
			nowInx = SHOUYU_COUNT;
		}else{
			nowInx = (Integer)obj;
		}
		
		
		if(nowInx + SHOUYU_COUNT >= tempList.size()){
			toInx = tempList.size();
		}else{
			toInx = nowInx + SHOUYU_COUNT;
		}
		JSONArray arrays = new JSONArray();
		JSONObject jobj = null;
		for(ExcelDataStudent eds : tempList.subList(nowInx , toInx )){
			jobj = new JSONObject();
			jobj.put("college", eds.getCollege());
			jobj.put("department", eds.getDepartment());
			jobj.put("classes", eds.getClasses());
			jobj.put("name", eds.getName());
			jobj.put("no", eds.getNo());
			jobj.put("inSchool", eds.getInSchool());
			jobj.put("phone", eds.getPhone());
			jobj.put("email", eds.getEmail());
			jobj.put("memo", eds.getMemo());
			arrays.add(jobj);
		}
		try {
			PrintWriter out = Struts2Utils.getResponse().getWriter();
			out.print(arrays.toString());
			out.flush();
			out.close();
			Struts2Utils.getSession().setAttribute("studentDataNowIdx", toInx);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}
	
	/**
	 * 提交
	 * <pre>把Excel数据保存到学生临时表里</pre>
	 * @return
	 */
	@SuppressWarnings("unchecked")
	@LogAnnotation(log = "基础数据导入 - 学生 - 提交")
	public String submit(){
		String msg = "";
		tempList = (List<ExcelDataStudent>)Struts2Utils.getSessionAttribute("studentDataExcelData");
		if(tempList == null){
			msg = "Session为空。请重新导入";
			return SUCCESS;
		}
		try {
			PrintWriter out = Struts2Utils.getResponse().getWriter();
			try {
				//上传之前先清掉临时数据
				studentTempManager.deleteAll();
				StudentTemp studentTemp = null;
				//遍历并写到数据库中
				for(ExcelDataStudent st : tempList){
					studentTemp = new StudentTemp();
					studentTemp.setClasses(st.getClasses());
					studentTemp.setCollege(st.getCollege());
					studentTemp.setDepartment(st.getDepartment());
					studentTemp.setEmail(st.getEmail());
					studentTemp.setName(st.getName());
					studentTemp.setNo(st.getNo());
					studentTemp.setStudentInSchoolDate(DateUtils.toDate(st.getInSchool()));
					studentTemp.setStudentMemo(st.getMemo());
					studentTemp.setTelephone(st.getPhone());
					studentTemp.setUserId(UserHolder.getLoginUser().getId());
					studentTemp.setYear(st.getYear());
					studentTempManager.save(studentTemp);
				}
				msg = "操作成功";
			} catch (Exception e) {
				e.printStackTrace();
				msg = "操作失败";
			}
			out.print(msg);
			out.flush();
			out.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return SUCCESS;
	}
	@Autowired
	public void setStudentTempManager(StudentTempManager studentTempManager) {
		this.studentTempManager = studentTempManager;
	}
	public File getUploadFile() {
		return uploadFile;
	}
	public void setUploadFile(File uploadFile) {
		this.uploadFile = uploadFile;
	}
	public String getUploadFileFileName() {
		return uploadFileFileName;
	}
	public void setUploadFileFileName(String uploadFileFileName) {
		this.uploadFileFileName = uploadFileFileName;
	}
	public String getUploadFileContentType() {
		return uploadFileContentType;
	}
	public void setUploadFileContentType(String uploadFileContentType) {
		this.uploadFileContentType = uploadFileContentType;
	}
	public List<ExcelDataError> getExcelErrors() {
		return excelErrors;
	}
	public void setExcelErrors(List<ExcelDataError> excelErrors) {
		this.excelErrors = excelErrors;
	}
	public List<ExcelDataStudent> getTempList() {
		return tempList;
	}
	public void setTempList(List<ExcelDataStudent> tempList) {
		this.tempList = tempList;
	}

	public int getSHOUYU_COUNT() {
		return SHOUYU_COUNT;
	}
}

